<template>
  <div>
    <mheader></mheader>
    <Row type="flex" justify="center" style="margin-top: 20px;">
      <Col span="13">
      <Card>
        <Tabs style="margin-bottom: 20px;" v-if="this.current===1">
          <TabPane label="支付页面">
            <div>
              <div style="font-size: 1.5rem; margin-bottom: 10px;">
                收货地址管理
                <a style="float: right; font-size: 1rem;" type="primary" @click="addAddress">
                  <Icon type="plus-round"></Icon>
                  新增地址</a>
              </div>
              <RadioGroup class="radio-group" v-model="addrId" size="large" vertical @on-change="selectAddr">
                <Radio v-for="(item,index) in addArr" :key="index" :label="item.id" class="radio-item">
                  <Icon type="person"></Icon>
                  <span>{{item.receiver}} / {{item.phone}} 收</span>
                  <div class="detail">
                    <mtag class="is-default" v-if="item.isDefault" tagv="默认地址"></mtag>
                    {{areaNameFormat(item.areaName)}}, {{item.detail}}
                  </div>
                  <div class="radio-extra">
                    <a @click="editAddress(index)">编辑</a> / <a @click="editAddress(item.id)">删除</a>
                  </div>
                </Radio>
              </RadioGroup>
            </div>
          </TabPane>
          <!--<TabPane label="电子票据">电子票据</TabPane>-->
        </Tabs>
        <template v-if="this.current===2">
          <Row>
            <div>
              <p class="tab-title">地址信息</p>
              <div class="address bottom-line">
                <div>收货人：<span>{{selectedAddr.receiver}}</span></div>
                <div>联系电话：<span>{{selectedAddr.phone}}</span></div>
                <div>邮政编码：<span>{{selectedAddr.postcode}}</span></div>
                <div>
                  收货地址：<span>{{areaNameFormat(selectedAddr.areaName)}}, {{selectedAddr.detail}}</span>
                </div>
              </div>
            </div>
          </Row>
          <Row>
            <div class="show top-line">
              <p class="tab-title">门票信息</p>
              <div class="show-poster">
                <img class="poster" :src="concert.poster.imageBase" alt="">
              </div>
              <div class="show-detail">
                <div class="title">
                  {{concert.title}}
                </div>
                <div class="price">
                  票面：<span>162 元</span>
                </div>
                <div class="place">
                  地点：<span>{{concert.place}}</span>
                </div>
                <div class="time">
                  时间：<span>2018.04.11 星期三 18:00</span>
                </div>
                <div class="count">
                  数量：<span>1</span> 张
                </div>
                <div class="total-price" style="margin-top: 20px;">
                  总价：<span style="color: #fd6857; font-size: 18px; font-weight: bold;">￥162元</span>
                </div>
              </div>
            </div>
          </Row>
          <Row>
            <div class="top-line">
              <p class="tab-title">支付方式</p>
              <RadioGroup v-model="payType">
                <Radio label="aliPay">支付宝</Radio>
                <Radio label="weChatPay">微信支付</Radio>
                <Radio label="cardPay">信用卡支付</Radio>
              </RadioGroup>
            </div>
          </Row>

        </template>
        <Button type="primary" @click="back" v-show="current > 0">上一步</Button>
        <Button type="primary" @click="next" v-show="current < 2">下一步</Button>
        <Button type="success" @click="handlePay" :loading="payLoading" v-show="current === 2">支付</Button>
      </Card>
      </Col>
      <Col span="3" style="margin-left: 20px;">
      <Card>
        <Steps :current="current" direction="vertical">
          <Step title="门票选择" content="请选择演出的门票信息"></Step>
          <Step title="完善信息" content="请补充完善个人信息"></Step>
          <Step title="订单预览" content="请确认完整的订单信息"></Step>
          <Step title="订单支付" content="请支付"></Step>
        </Steps>
      </Card>
      </Col>
    </Row>
    <mfooter></mfooter>
    <Modal v-model="showModal" :title="title" @on-ok="saveAddress">
      <Form class="step-form" :model="formInfo" label-position="right" :label-width="100">
        <FormItem label="收货人姓名">
          <Input v-model="formInfo.receiver"></Input>
        </FormItem>
        <FormItem label="电话号码">
          <Input v-model="formInfo.phone"></Input>
        </FormItem>
        <FormItem label="所在地区">
          <al-cascader v-model="formInfo.area" level="2"/>
        </FormItem>
        <FormItem label="详细地址">
          <Input v-model="formInfo.detail"></Input>
        </FormItem>
        <FormItem label="邮政编码">
          <Input v-model="formInfo.postcode"></Input>
        </FormItem>
        <FormItem>
          <Checkbox v-model="formInfo.isDefault">设置默认地址</Checkbox>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
  import mheader from "@/components/mheader";
  import mfooter from "@/components/mfooter";
  import mtag from "@/components/mtag";
  import Cookies from "js-cookie";

  export default {
    name: "pay",
    components: {
      mheader,
      mfooter,
      mtag,
    },
    data() {
      return {
        current: 1,
        customer: {},
        showModal: false,
        editFlag: false,
        payLoading: false,
        payType: '',
        tempValue: {},
        concert: {},
        goods: {},
        item: {},
        purchase:{},
        addrId: '',
        addArr: [],
        selectedAddr: {},
        title: '',
        formInfo: {area: []},
        addrNode: {
          receiver: '',
          phone: '',
          area: [],
          detail: '',
          postcode: '',
          isDefault: false
        }
      }
    },
    methods: {
      next() {
        if (this.current < 3) {
          this.current++;
        }
      },
      back() {
        if (this.current > 0) {
          this.current--;
        }
      },
      loadConcert(id) {
        this.$axios({
          method: 'get',
          url: `/api/concert/${id}`,
        }).then((res) => {
          let data = res.data;
          this.concert = data.result[0];
          this.loadImage(this.concert.poster);
        });
      },
      loadImage(imageId) {
        this.$axios({
          method: 'get',
          url: `/api/image/${imageId}`,
        }).then((res) => {
          this.concert.poster = res.data;
        })
      },
      loadAddress() {
        this.$axios({
          method: 'get',
          url: '/api/address',
          params: {
            cid: this.customer.id
          }
        }).then(res => {
          this.addArr = res.data.result;
          this.addArr.forEach(e=> {
            e.area = JSON.parse(e.areaName);
          });
          this.selectedAddr = this.addArr.find(e => e.isDefault);
          this.addrId = this.selectedAddr.id;
        });
      },
      addAddress() {
        this.title = '添加地址';
        this.formInfo = Object.assign({}, this.addrNode);
        this.editFlag = false;
        this.showModal = true;
      },
      editAddress(index) {
        this.title = '编辑地址';
        this.editFlag = true;
        const addr = this.addArr[index];
        this.formInfo = Object.assign({}, addr);
        this.showModal = true;
      },
      saveAddress() {
        if (this.customer !== undefined) {
          let area = this.formInfo.area;
          if (area.length > 0) {
            let area_code = [];
            let area_name = [];
            area.forEach(e => {
              area_code.push(e.code);
              area_name.push(e.name);
            });
            this.formInfo['areaCode'] = JSON.stringify(area_code);
            this.formInfo['areaName'] = JSON.stringify(area_name);
          }
          let url = '/api/address';
          if (this.editFlag) {
            url = url + `/${this.formInfo.id}`;
          }
          this.formInfo.parentId = this.customer.id;
          this.$axios({
            method: 'post',
            url: url,
            data: {
              address: this.formInfo,
            }
          }).then((res) => {
            if (res.data) {
              this.$Notice.success({
                title: '保存成功!'
              });
              this.loadAddress();
            } else {
              this.$Notice.error({
                title: '保存失败!'
              });
            }
          });
        }
        this.showModal = false;
      },
      removeAddress(addressId) {
        this.$axios({
          method: 'delete',
          url: `/api/address/${addressId}`,
        }).then((res) => {
          if (res.data) {
            this.$Notice.success({
              title: '删除成功!'
            });
          } else {
            this.$Notice.error({
              title: '删除失败!'
            });
          }
        });
      },
      selectAddr(data) {
        this.selectedAddr = this.addArr.find(e=>e.id === this.addrId);
      },
      areaNameFormat(name) {
        if (name !== undefined) {
          return JSON.parse(name).join(", ");
        }
      },
      handleBeforePay() {
        this.payLoading = true;
        this.purchase['customerId'] = this.customer.id;
        this.purchase['itemId'] = this.item.id;
        this.purchase['itemType'] = this.item.type;
        this.purchase['title'] = this.item.title;
        this.purchase['detail'] = this.item.detail;
        this.purchase['price'] = this.item.price;
        this.purchase['count'] = this.item.count;
        this.purchase['total'] = this.item.total;
        this.purchase['payType'] = this.payType;
        this.purchase['areaName'] = this.selectedAddr.areaName;
        this.purchase['address'] = this.selectedAddr.detail;
      },
      handlePay() {
        this.handleBeforePay();
        setTimeout(() => {
          this.finishPay();
        }, 2000);
      },
      finishPay() {
        this.$axios({
          method: 'post',
          url: '/api/purchase',
          data: {
            purchase: this.purchase,
          }
        }).then(res => {
          console.log(res);
          this.payLoading = false;
        }).catch(t => {
          this.payLoading = false;
        });
      }
    },
    mounted() {
      this.item = sessionStorage.getItem('item');
      let itemId = this.$route.params.id;
      let type = this.$route.params.type;
      if (type===0) {
        this.loadConcert(itemId);
      }
      if (Cookies.get('customer') !== undefined) {this.customer = JSON.parse(Cookies.get('customer'))};
      if (this.item === undefined || this.item === null) {
        this.$router.push({name: 'Error403'})
      } else {
        this.item = JSON.parse(this.item);
        this.loadAddress();
      }
    },
    beforeDestroy() {
      sessionStorage.removeItem('item');
    }
  }
</script>

<style scoped>

  .top-line {
    border-top: dashed 2px #eee;
    padding-top: 20px;
  }
  .tab-title {
    color: #464c5b;font-weight: bold; font-size: 20px;
  }

  .radio-group {
    width: 100%;
  }

  .radio-item {
    width: 100%;
    height: 65px;
    border-bottom: dashed 2px #eee;
    padding-left: 40px;
    margin-top: 10px;
  }

  .radio-item > .detail {
    margin-top: -5px;
    margin-left: 25px;
  }

  .radio-item > .detail > .is-default {
    margin-top: -5px;
    margin-right: 5px;
  }

  .radio-extra {
    margin-top: -50px;
    float: right;
  }
  .address {
    margin: 5px 0 30px 20px;
  }
  .address > div {
    margin-top: 5px;
    font-size: 16px;
    color: #151515;
  }
  .address > div > span {
    color: gray;
    font-size: 14px;
  }
  .show {
    margin-bottom: 20px;
  }
  .show-poster {
    margin: 10px 0 10px 20px;
    width: 150px;
    float:left;
  }
  .show-poster > .poster {
    width: 100%;
    height: 100%;
    border-radius: 6px;
  }
  .show-detail {
    margin: 10px 0 10px 40px;
    float: left;
    font-size: 16px;
    color: #151515;
  }
  .title {
    color: #080306;
    font-weight: bold;
  }
  .show-detail > div {
    margin-top: 5px;
  }
  .show-detail > div > span {
    color: gray;
    font-size: 14px;
  }

</style>
